/*
 * Copyright (c) 1994-2017, Joyoung Stock CO.LTD.
 * The FWJR Project.
 * All Rights Reserved.
 */

package com.qdsg.ysg.doctor.ui.dialog;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.qdsg.ysg.doctor.R;
import com.qdsg.ysg.doctor.base.BaseDialogFragment;
import com.qdsg.ysg.doctor.util.DpUtil;
import com.qdsg.ysg.doctor.util.SoftKeyboardUtil;
import com.qdsg.ysg.doctor.util.ToastUtil;
import com.qdsg.ysg.doctor.util.UtilString;
import com.rest.business.RestProxy;
import com.rest.response.BaseStringResponse;
import com.rest.response.MedicineDetailResponse;
import com.rest.response.MedicineResponse;
import com.rest.response.PrescriptionResponse;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;


/**
 * @author DELL
 */
public class MedicineDialog extends BaseDialogFragment {
    private OnItemClickListener mListener;
    private Dialog mDialog;
    private EditText edt_search, edt_medicine_name, edt_medicine_dose, edt_medicine_num;
    private RecyclerView recyclerView;
    private LinearLayout first, second;
    private TextView tv_use;
    private TextView tv_frequent;
    //    private TextView tv_medicine_dose;
    private TextView tv_medicine_num;
    private TextView tv_where;
    private ImageView btn_cancel;
    private RelativeLayout rl_frequent, rl_use, rl_where;
    List<MedicineResponse.Medicine> list = new ArrayList<>();
    //    List<MedicineDetailResponse.Medicine> listDetail = new ArrayList<>();
    AddMedicineAdapter adapter;
    PrescriptionResponse.Prescription p = new PrescriptionResponse.Prescription();
    private String specialUnit, siteId;
    private Boolean isGuoYao = false;
    private ItemDialog mItemDialog = null;

    public static MedicineDialog newInstance(int type) {
        Bundle args = new Bundle();
        args.putInt("type", type);
        MedicineDialog fragment = new MedicineDialog();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    @NonNull
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        mDialog = super.onCreateDialog(savedInstanceState);
        mDialog.setCancelable(false);
        Window window = mDialog.getWindow();
        if (window != null) {
            window.setGravity(Gravity.BOTTOM);
        }
        return mDialog;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View mView = inflater.inflate(R.layout.dialog_medicine, container, false);
        mView.setMinimumWidth(mScreenWidth);
        edt_search = mView.findViewById(R.id.edt_search);
        edt_medicine_name = mView.findViewById(R.id.edt_medicine_name);
        edt_medicine_dose = mView.findViewById(R.id.edt_medicine_dose);
        edt_medicine_num = mView.findViewById(R.id.edt_medicine_num);
        tv_where = mView.findViewById(R.id.tv_where);
//        tv_medicine_dose = mView.findViewById( R.id.tv_medicine_dose );
        tv_medicine_num = mView.findViewById(R.id.tv_medicine_num);
        first = mView.findViewById(R.id.first);
        second = mView.findViewById(R.id.second);
        TextView btn_confirm = mView.findViewById(R.id.btn_confirm);
        btn_cancel = mView.findViewById(R.id.btn_cancel);
        tv_use = mView.findViewById(R.id.tv_use);
        tv_frequent = mView.findViewById(R.id.tv_frequent);
        rl_frequent = mView.findViewById(R.id.rl_frequent);
        rl_use = mView.findViewById(R.id.rl_use);
        rl_where = mView.findViewById(R.id.rl_where);
        LinearLayoutManager manager = new LinearLayoutManager(getActivity());
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView = mView.findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(manager);
        adapter = new AddMedicineAdapter();
        recyclerView.setAdapter(adapter);
        recyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void onDraw(@NotNull Canvas c, @NotNull RecyclerView parent, @NotNull RecyclerView.State state) {
                super.onDraw(c, parent, state);
            }

            @Override
            public void getItemOffsets(@NotNull Rect outRect, @NotNull View view, @NotNull RecyclerView parent, @NotNull RecyclerView.State state) {
                super.getItemOffsets(outRect, view, parent, state);
                outRect.bottom = DpUtil.dip2px(Objects.requireNonNull(getActivity()), 1);
            }
        });
        assert getArguments() != null;
        int type = getArguments().getInt("type");
        if (type == 1) {
            //国药
            isGuoYao = true;
        }

        getMedicineList(getArguments().getInt("type"));

        rl_frequent.setOnClickListener(v -> showSelectHeadPicDialog(0));
        rl_use.setOnClickListener(v -> showSelectHeadPicDialog(1));
//        rl_where.setOnClickListener(v -> showSelectHeadPicDialog(5));
        btn_confirm.setOnClickListener(v -> {

            //判断数量是否为0
            String shuliang = edt_medicine_num.getText().toString().trim();
            String jiliang = edt_medicine_dose.getText().toString().trim();
            String pinlv = tv_frequent.getText().toString().trim();
//            String where = tv_where.getText().toString().trim();
            String tujing = tv_use.getText().toString().trim();

            if (UtilString.isEmpty(jiliang)) {
                ToastUtil.showToast(mContext, "药品剂量不能为空");
                return;
            }
            if (UtilString.isEmpty(pinlv)) {
                ToastUtil.showToast(mContext, "使用频率不能为空");
                return;
            }
//            if (UtilString.isEmpty( where )) {
//                ToastUtil.showToast( mContext, "用药部位不能为空" );
//                return;
//            }
            if (UtilString.isEmpty( tujing )) {
                ToastUtil.showToast( mContext, "药品用法不能为空" );
                return;
            }

            if (UtilString.isEmpty(shuliang)) {
                ToastUtil.showToast(mContext, "药品数量不能为空");
            } else if (Integer.parseInt(shuliang) <= 0) {
                ToastUtil.showToast(mContext, "药品数量必须大于0");
            } else {
                p.drugChannel = tv_use.getText().toString();
                p.drugDose = edt_medicine_dose.getText().toString();
                //剂量，瓶/支
                p.specialUnit = specialUnit;
                p.drugFrequency = tv_frequent.getText().toString();
                p.drugNumber = edt_medicine_num.getText().toString();//药品数量
                p.drugPosition = tv_where.getText().toString();
                queryPrice(shuliang);
            }
        });
        btn_cancel.setOnClickListener(v -> {
            SoftKeyboardUtil.hideSoftKeyboard(Objects.requireNonNull(getActivity()));
            dismiss();
        });
        edt_search.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                // 按下完成按钮，这里和上面imeOptions对应
                if (getArguments() != null) {
                    getMedicineList(getArguments().getInt("type"));
                }
                SoftKeyboardUtil.hideSoftKeyboard(Objects.requireNonNull(getActivity()));
            }
            return false;
        });

        Objects.requireNonNull(Objects.requireNonNull(getDialog()).getWindow()).setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
        return mView;
    }

    @Override
    public void onViewCreated(@NotNull View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        Objects.requireNonNull(getDialog()).setCanceledOnTouchOutside(false);
    }

    public interface OnItemClickListener {
        void callback(PrescriptionResponse.Prescription p);

    }

    public void setOnItemClickListener(OnItemClickListener listener) {
        this.mListener = listener;
    }

//    @Override
//    public void onClick(View view) {
//        switch (view.getId()) {
//            case R.id.tv_check: {
//                mListener.check();
//                dismiss();
//            }
//            break;
//            case R.id.tv_refuse: {
//                mListener.refuse();
//                dismiss();
//            }
//            break;
//            case R.id.txt_cancel: {
//                dismiss();
//            }
//            break;
//            default:
//                break;
//        }
//    }

    public boolean isShowing() {
        return mDialog != null && mDialog.isShowing();
    }


    class AddMedicineAdapter extends RecyclerView.Adapter<AddMedicineAdapter.Holder> {


        @NotNull
        @Override
        public AddMedicineAdapter.Holder onCreateViewHolder(@NotNull ViewGroup parent, int viewType) {
            return new Holder(LayoutInflater.from(getActivity()).inflate(R.layout.item_search_medicine, parent, false));
        }

        @SuppressLint("SetTextI18n")
        @Override
        public void onBindViewHolder(AddMedicineAdapter.Holder holder, final int position) {
            holder.itemView.setLayoutParams(new RelativeLayout.LayoutParams(recyclerView.getWidth(), ViewGroup.LayoutParams.WRAP_CONTENT));
            holder.itemView.setOnClickListener(v -> {
                //隐藏药品列表,展示药品计量
                first.setVisibility(View.GONE);
                second.setVisibility(View.VISIBLE);
                p.westernId = list.get(position).id;
                p.code = list.get(position).code;
                siteId = list.get(position).id;//药品ID
                p.name = list.get(position).name;
                p.dosageUnit = list.get(position).dosageUnit;
                edt_medicine_name.setText(list.get(position).name);
                tv_medicine_num.setText(list.get(position).outPatientUnit);
                if (isGuoYao) {
                    //国药没有默认
//                    tv_medicine_dose.setText( list.get( position ).specialUnit + "/次" );
                    specialUnit = list.get(position).specialUnit;
                } else {
                    queryWesternById(list.get(position).id, position);
                }
            });
            holder.tv_name.setText(list.get(position).name + " " + list.get(position).drugSpecification);
            holder.tv_make.setText(list.get(position).manufacturer);
        }

        @Override
        public int getItemCount() {
            return list.size();
        }

        class Holder extends RecyclerView.ViewHolder {

            TextView tv_name, tv_make;

            Holder(View itemView) {
                super(itemView);
                tv_name = itemView.findViewById(R.id.tv_name);
                tv_make = itemView.findViewById(R.id.tv_make);
            }
        }
    }


    private void getMedicineList(int type) {
        RestProxy.getInstance().getMedicineList("", edt_search.getText().toString(), type + "", new Observer<MedicineResponse>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @SuppressLint("NotifyDataSetChanged")
            @Override
            public void onNext(MedicineResponse medicineResponse) {
                try {
                    list.clear();
                    list.addAll(medicineResponse.data);
                    adapter.notifyDataSetChanged();
                } catch (Exception e) {
                    // 捕获异常，如果要捕获Json数据异常，写catch(JSONException e)
                    e.printStackTrace();
                    //打印出来就Log.e(TAG,Log.getStackTraceString(e));
                }
            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
                ToastUtil.onError(getActivity(), e);
            }

            @Override
            public void onComplete() {

            }
        });
    }


    /**
     * 查询药品的默认值
     *
     * @time 2020/11/23 14:01
     */
    private void queryWesternById(String id, int position) {
        RestProxy.getInstance().queryWesternById(id, new Observer<MedicineDetailResponse>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @SuppressLint("SetTextI18n")
            @Override
            public void onNext(MedicineDetailResponse medicineDetailResponse) {
                try {
                    if (medicineDetailResponse != null) {
                        if (!UtilString.isEmpty(medicineDetailResponse.data.useNumber)) {
                            //默认剂量
                            edt_medicine_dose.setText(medicineDetailResponse.data.useNumber);
                        }
                        //默认给药频率
                        tv_frequent.setText(medicineDetailResponse.data.frequency);
                        p.drugFrequency = medicineDetailResponse.data.frequency;
                        p.drugFrequencyCode = medicineDetailResponse.data.frequencyCode;
//                        if (!UtilString.isEmpty(medicineDetailResponse.data.frequencyCode)) {
//                            //默认给药频率
//                            tv_frequent.setText(medicineDetailResponse.data.frequencyCode);
//                        }
                        //用法
                        tv_use.setText(medicineDetailResponse.data.drugUsing);
                        p.drugChannel  = medicineDetailResponse.data.drugUsing;
                        p.drugChannelCode  = medicineDetailResponse.data.drugUsingCode;
//                        if (!UtilString.isEmpty(medicineDetailResponse.data.drugUsing)) {
//                            //用法
//                            tv_use.setText(medicineDetailResponse.data.drugUsing);
//                        }

                    } else {
//                        tv_medicine_dose.setText( list.get( position ).specialUnit + "/次" );
//                        specialUnit = list.get( position ).specialUnit;
                    }
                } catch (Exception e) {
                    // 捕获异常，如果要捕获Json数据异常，写catch(JSONException e)
                    e.printStackTrace();
                    //打印出来就Log.e(TAG,Log.getStackTraceString(e));
                }
            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
                ToastUtil.onError(getActivity(), e);
            }

            @Override
            public void onComplete() {

            }
        });
    }

    /**
     * 计算单个药品开出的价格
     *
     * @time 2020/11/23 14:01
     */
    private void queryPrice(String number) {
        RestProxy.getInstance().queryPrice(siteId, number, new Observer<BaseStringResponse>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(BaseStringResponse baseStringResponse) {
                try {
                    if (baseStringResponse != null) {
                        p.expense = baseStringResponse.data;
                        mListener.callback(p);
                        if (!UtilString.isEmpty(edt_medicine_num.getText().toString().trim())) {
                            SoftKeyboardUtil.hideFraSoftKeyboard(getActivity(), edt_medicine_num);
                        }
                        if (!UtilString.isEmpty(edt_medicine_dose.getText().toString().trim())) {
                            SoftKeyboardUtil.hideFraSoftKeyboard(getActivity(), edt_medicine_dose);
                        }
                        dismiss();
                    }
                } catch (Exception e) {
                    // 捕获异常，如果要捕获Json数据异常，写catch(JSONException e)
                    e.printStackTrace();
                    //打印出来就Log.e(TAG,Log.getStackTraceString(e));
                }
            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
                ToastUtil.onError(getActivity(), e);
            }

            @Override
            public void onComplete() {

            }
        });
    }


    private void showSelectHeadPicDialog(final int type) {
        // 初始化点击头像弹出的对话框
        mItemDialog = ItemDialog.newInstance(type, siteId, isGuoYao);
        mItemDialog.setOnItemClickListener((s, id) -> {
            if (type == 0) {
                p.drugFrequencyCode = id;
                tv_frequent.setText(s);
            } else if (type == 1) {
                p.drugChannelCode = id;
                tv_use.setText(s);
            } else if (type == 5) {
                tv_where.setText(s);
            }
        });
        mItemDialog.show(getChildFragmentManager(), "mItemDialog");
    }
}
